package info.batcloud.fanli.core.item.collection;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctospace.archit.common.pagination.Paging;
import com.taobao.api.TaobaoClient;
import info.batcloud.fanli.core.dto.CommissionItemFetchDTO;
import info.batcloud.fanli.core.constants.TaobaoClientConstants;
import info.batcloud.fanli.core.enums.CommissionItemStatus;
import info.batcloud.fanli.core.enums.EcomPlat;
import info.batcloud.fanli.core.enums.ItemSelectionType;
import info.batcloud.fanli.core.helper.QueryStringHelper;
import info.batcloud.fanli.core.service.ShopcatService;
import info.batcloud.fanli.core.service.SystemSettingService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.function.Consumer;

@Service
public class DataokeSelectionCollectorSelection extends AbstractItemSelectionCollector<DataokeSelectionCollectorSelection.DataokeContext> {

    private static final Logger logger = LoggerFactory.getLogger(DataokeSelectionCollectorSelection.class);

    @Inject
    @Qualifier(TaobaoClientConstants.TAOBAO_CLIENT_ITEM_TBK)
    private TaobaoClient taobaoClient;

    @Inject
    private SystemSettingService systemSettingService;

    @Inject
    private ShopcatService shopcatService;

    @Override
    public CollectResult collect(DataokeSelectionCollectorSelection.DataokeContext context, Consumer<Paging<CommissionItemFetchDTO>> pagingConsumer) {

        CollectResult result = new CollectResult();
        String url = context.getApiUrl();
        int page = context.getStartPage();
        int pageSize = context.getPageSize();
        try {
            int num = 0;
            while (true) {
                logger.info("大淘客选品抓取" + page + "页");
                Map<String, String> map = new HashMap<>();
                map.put("page", page + "");
                url = QueryStringHelper.serialize(url, map);
                String jsonStr = IOUtils.toString(new URL(url));
                JSONObject data = JSON.parseObject(jsonStr);
                JSONArray jsonArray = data.getJSONArray("result");
                List<CommissionItemFetchDTO> commissionItemFetchDTOList = this.toCommissionItemFetchBO(context, jsonArray);
                Paging<CommissionItemFetchDTO> paging = new Paging<>();
                int total = data.getJSONObject("data").getInteger("total_num");
                paging.setTotal(total);
                paging.setPage(page);
                paging.setPageSize(context.getPageSize());
                paging.setResults(commissionItemFetchDTOList);
                pagingConsumer.accept(paging);
                num += jsonArray.size();
                if (jsonArray.size() == 0 || page * pageSize >= total) {
                    break;
                }
                if (page >= context.getMaxPage()) {
                    break;
                }
                page++;
            }
            logger.info("搜索完成");
            result.setSuccess(true);
            result.setTotalNum(num);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    private List<CommissionItemFetchDTO> toCommissionItemFetchBO(DataokeSelectionCollectorSelection.DataokeContext context, JSONArray list) {
        List<CommissionItemFetchDTO> dtoList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject mapData = (JSONObject) list.get(i);
            CommissionItemFetchDTO dto = new CommissionItemFetchDTO();
            Date now = new Date();
            dto.setListTime(now);
            /**
             * 商品的下架时间为当前的日期+7天，优惠券的下架时间，活动的下架时间取最大者
             * */
            Date delistTime = DateUtils.addDays(now, 7);
            Date couponEndTime = mapData.getDate("Quan_time");
            if (couponEndTime != null) {
                delistTime = couponEndTime;
            }
            dto.setCouponEndTime(couponEndTime);
            dto.setCouponStartTime(new Date());
            dto.setDelistTime(Collections.max(Arrays.asList(delistTime, couponEndTime)));
//            dto.setShopTitle(StringUtils.defaultString(mapData.getShopTitle(), ""));
            dto.setCouponRemainCount(mapData.getIntValue("Quan_surplus"));
            dto.setCouponTotalCount(mapData.getIntValue("Quan_receive") + mapData.getIntValue("Quan_surplus"));
            dto.setCoupon(true);
            dto.setDescription(mapData.getString("Introduce"));
//            dto.setSummary(mapData.getItemDescription());
            dto.setCouponValue(mapData.getFloatValue("Quan_price"));
            dto.setSourceItemUrl(mapData.getString("Quan_link"));
            dto.setSourceItemId(mapData.getLong("GoodsID"));
            dto.setTitle(mapData.getString("Title"));
            dto.setSourceItemClickUrl(mapData.getString("Quan_link"));
            dto.setCouponClickUrl(mapData.getString("Quan_link"));
            dto.setOriginPrice(mapData.getFloatValue("Org_Price"));
            dto.setCouponThresholdAmount(dto.getOriginPrice() - 1);
            float commissionRate = mapData.getFloatValue("Commission");
            dto.setCommissionRate(commissionRate);

            dto.setEcomPlat(mapData.getIntValue("IsTmall") == 1 ? EcomPlat.TMALL : EcomPlat.TAOBAO);
            dto.setImgList(new ArrayList<>());
            dto.setPicUrl(mapData.getString("Pic"));
            dto.setSales(mapData.getIntValue("Sales_num"));
            dto.setStatus(CommissionItemStatus.ONSALE);
            dto.setChannelId(context.getChannelId());
            dto.setRecommend(context.isRecommend());
            dto.setShopcatId(context.getShopcatId());
            dtoList.add(dto);
        }
        return dtoList;
    }

    @Override
    public Class<DataokeContext> getContextType() {
        return DataokeContext.class;
    }

    @Override
    protected ItemSelectionType getItemSelectionType() {
        return ItemSelectionType.DATAOKE;
    }

    public static class DataokeContext extends Context {
        private String apiUrl;

        public String getApiUrl() {
            return apiUrl;
        }

        public void setApiUrl(String apiUrl) {
            this.apiUrl = apiUrl;
        }
    }
}
